package com.yf.exam.modules.ai.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.web.client.RestTemplate;

import java.util.*;

@Api(tags = {"AI 解析"})
@RestController
@RequestMapping("/exam/api/ai")
public class AiController {

    @Value("${ai.base-url:https://api.openai.com}")
    private String baseUrl;

    @Value("${ai.api-key:}")
    private String apiKey;

    @Value("${ai.model:gpt-4o-mini}")
    private String model;

    private final RestTemplate restTemplate = new RestTemplate();

    @ApiOperation("根据题目生成AI解析")
    @PostMapping("/analysis")
    public Map<String, Object> analysis(@RequestBody Map<String, Object> payload) {
        String content = String.valueOf(payload.getOrDefault("content", ""));
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> answers = (List<Map<String, Object>>) payload.getOrDefault("answers", Collections.emptyList());

        StringBuilder prompt = new StringBuilder();
        prompt.append("你是一名资深教研老师，请用中文给出简洁、逻辑清晰的解析。\n");
        prompt.append("题目：").append(content).append("\n");
        if (!answers.isEmpty()) {
            prompt.append("选项：\n");
            for (Map<String, Object> item : answers) {
                Object tag = item.getOrDefault("tag", "");
                Object text = item.getOrDefault("content", "");
                prompt.append(tag).append(". ").append(text).append("\n");
            }
        }
        prompt.append("请按以下格式输出：\n");
        prompt.append("1) 正确选项\n2) 关键点\n3) 详细解析（≤180字）\n");

        Map<String, Object> result = new HashMap<>();

        if (apiKey == null || apiKey.trim().isEmpty()) {
            result.put("code", 0);
            result.put("data", "未配置AI密钥，无法调用外部模型。可在 application-*.yml 中设置 ai.api-key。");
            return result;
        }

        try {
            String url = baseUrl.endsWith("/") ? baseUrl + "v1/chat/completions" : baseUrl + "/v1/chat/completions";

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.setBearerAuth(apiKey);

            Map<String, Object> body = new HashMap<>();
            body.put("model", model);
            List<Map<String, String>> messages = new ArrayList<>();
            messages.add(new HashMap<String, String>() {{
                put("role", "user");
                put("content", prompt.toString());
            }});
            body.put("messages", messages);
            body.put("temperature", 0.2);

            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(body, headers);
            ResponseEntity<Map<String, Object>> resp = restTemplate.exchange(
                    url,
                    HttpMethod.POST,
                    entity,
                    new ParameterizedTypeReference<Map<String, Object>>() {}
            );
            Map<String, Object> bodyMap = resp.getBody();
            String text = parseOpenAI(bodyMap);
            result.put("code", 0);
            result.put("data", text);
            return result;
        } catch (Exception e) {
            result.put("code", -1);
            result.put("data", "AI服务调用失败：" + e.getMessage());
            return result;
        }
    }

    private String parseOpenAI(Map<String, Object> body) {
        if (body == null) return "";
        Object choicesObj = body.get("choices");
        if (choicesObj instanceof List) {
            List<?> choices = (List<?>) choicesObj;
            if (!choices.isEmpty()) {
                Object first = choices.get(0);
                if (first instanceof Map) {
                    Map<?, ?> fm = (Map<?, ?>) first;
                    Object message = fm.get("message");
                    if (message instanceof Map) {
                        Object content = ((Map<?, ?>) message).get("content");
                        return content == null ? "" : String.valueOf(content);
                    }
                    Object text = fm.get("text");
                    return text == null ? "" : String.valueOf(text);
                }
            }
        }
        return "";
    }
}


